package com.bang.daybreak.security.config.handler;

import com.bang.daybreak.common.util.JWTUtils;
import com.bang.daybreak.common.util.JacksonUtils;
import com.bang.daybreak.security.model.SysUserDetails;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * <p>
 *     登录成功后用户，返回json。
 * </p>
 *
 * @version 1.0
 * @author: wdj
 * @date: 2019/8/10 0010 下午 17:39
 */
@Slf4j
@Component
public class IdentityAuthenticationSuccessHandler implements AuthenticationSuccessHandler {


    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse
            , Authentication authentication) throws IOException, ServletException {

        SysUserDetails sysUserDetails = (SysUserDetails)authentication.getPrincipal();
        // 创建token
        Map<String, Object> claims = new HashMap<>(1);
        claims.put("userId", sysUserDetails.getSysUser().getUserId());

        String token = JWTUtils.createToken(claims);
        Map<String, Object> map = new LinkedHashMap<String, Object>();
        map.put("token", token);
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        httpServletResponse.setStatus(200);
        httpServletResponse.getWriter().write(JacksonUtils.toJson(map));
        /**
         *
         * TODO。记录日志
         */

    }
}
